import orderApi from '@/api/orderApi'
import type { IModalDetail } from '@/types/modal'
import type { OrderItem, OrderRoute } from '@/types/orderType'
import { message } from '@/utils/AntdGlobal'
import { Modal } from 'antd'
import { useImperativeHandle, useState } from 'react'
import { flushSync } from 'react-dom'

const OrderMark = (props: IModalDetail) => {
  const [visible, setVisible] = useState(false)
  const [orderId, setOrderId] = useState<string>()
  const [markers, setMarkers] = useState<{ lng: string; lat: string; id: number }[]>([])
  useImperativeHandle(props.mRef, () => {
    return {
      open
    }
  })
  const open = async (orderId: string) => {
    setOrderId(orderId)
    flushSync(() => {
      setVisible(true)
    })
    const detail = await orderApi.getOrderDetail(orderId)
    renderMap(detail)
  }
  const renderMap = (detail: OrderItem) => {
    const map = new window.BMapGL.Map('map') // 创建Map实例
    map.centerAndZoom(detail.cityName, 12) // 初始化地图,设置中心点坐标和地图级别
    map.addEventListener('click', e => {
      createMarker(map, e.latlng.lat, e.latlng.lng)
    })
    if (detail.route) {
      detail.route.forEach(item => {
        createMarker(map, item.lat, item.lng)
      })
    }
  }
  const createMarker = (map: any, lat: string, lng: string) => {
    const id = Math.random()
    const marker = new window.BMapGL.Marker(new window.BMapGL.Point(lng, lat))
    const menu = new window.BMapGL.ContextMenu()
    markers.push({ lat, lng, id })
    marker.id = id
    menu.addItem(
      new window.BMapGL.MenuItem('删除', () => {
        map.removeOverlay(marker)
        const index = markers.findIndex(item => item.id === id)
        markers.splice(index, 1)
        setMarkers(markers)
      })
    )
    setMarkers(markers)
    marker.addContextMenu(menu)
    map.addOverlay(marker)
  }
  const handleOk = async () => {
    await orderApi.updateOrderInfo({ orderId, route: markers } as unknown as OrderRoute)
    message.success('轨迹更新成功')
    handleCancel()
  }
  const handleCancel = () => {
    setVisible(false)
    setMarkers([])
  }
  return (
    <Modal
      width={800}
      open={visible}
      title='地图打点'
      okText='确定'
      cancelText='取消'
      onOk={handleOk}
      onCancel={handleCancel}
    >
      <div id='map' style={{ height: 500 }}></div>
    </Modal>
  )
}

export default OrderMark
